const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const config = require('./configuration');
const mongoClient = require('./external/mongoClient');

const { router: aquireRouter } = require('./routers/acquireRouters');
const { showRequestMiddleware } = require('./middlewares/showRequestMiddleware');
const { identificationMiddleware } = require('./middlewares/identificatoinMiddleware');
const { healthCheckUtils } = require('./utilities/healthcheck');

const app = express();

const server = http.Server(app);
server.listen(config.PORT, () => {
  console.log('Server Start with listening at ', config.PORT);

});

app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '5mb' }));
app.use(cookieParser());


app.use(showRequestMiddleware);

// healthCheck
app.get('/healthCheck', healthCheckUtils({ redis: true, mongo: true }));

app.use('/api/v1/aquire', aquireRouter);


app.get('/', async(req, res, next) => {
  res.status(200).json({
    message: 'hello, world!, This is api builder platform',
  });
});

process.on('SIGINT', () => {
  mongoClient.releaseDB().then(() => {
    console.log('db has been closed already!');
    process.exit(0);
  });
});

process.on('SIGABRT', () => {
  process.exit(1);
});

process.on('SIGTERM', () => {
  process.exit(127);
});
